package cn.cs.yangtai.controller;


import cn.cs.yangtai.entity.Comminicate;
import cn.cs.yangtai.service.ComminicateService;
import com.baidubce.appbuilder.base.exception.AppBuilderServerException;
import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient;
import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator;
import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Date;

@RestController
@Slf4j
@Tag(name = "AI问答")
@RequestMapping("/ai")
public class AIController {
    @Autowired
    private ComminicateService comminicateService;
    @Value("${wxyy.APPBUILDER_TOKEN}")
    private String APPBUILDER_TOKEN;
    @Value("${wxyy.appId}")
    private String appId;


    @GetMapping("/getAI")
    @Operation(summary = "获取AI问答")
    public String getAI(String question,Integer userId) throws IOException, AppBuilderServerException {
        //文心一言开发者TOKEN
        System.setProperty("APPBUILDER_TOKEN", APPBUILDER_TOKEN);
        //创建的应用ID
        AppBuilderClient client = new AppBuilderClient(appId);
        //创建会话
        String conversation = client.createConversation();
        //会话迭代器，用于获取会话的回复。question用户提问，conversation会话ID，new String[]{}回答，stream是否流式返回，默认为false
        AppBuilderClientIterator itor = client.run(question, conversation, new String[]{}, false);
        StringBuilder answer = new StringBuilder();
        while (itor.hasNext()) {
            AppBuilderClientResult response = itor.next();
            answer.append(response.getAnswer());
        }
        System.out.println(answer);
        if(answer != null){
            Comminicate comminicate = new Comminicate();
            comminicate.setIUserId(userId);
            comminicate.setQuestion(question);
            comminicate.setAnswer(answer.toString());
            comminicate.setIDate(new Date());
            try {
                comminicateService.insert(comminicate);
            }catch (Exception e){
                log.info("AI问答记录失败");
                return "AI问答记录失败";
            }

            log.info("AI问答记录成功");
        }
        return answer.toString();
    }


}
